<template>
  <div class="app-container">

    <!--搜索表单-->
    <div class="search-container">
      <el-form :inline="true" :model="searchForm" class="search-form" @submit.native.prevent>
        <el-form-item label="姓名">
          <el-input
            v-model="searchForm.name"
            placeholder="请输入员工姓名"
            clearable
            size="small"
          />
        </el-form-item>
        <el-form-item label="性别">
          <el-select v-model="searchForm.gender" placeholder="请选择" clearable size="small">
            <el-option label="男" value="1" />
            <el-option label="女" value="2" />
          </el-select>
        </el-form-item>

        <el-form-item label="入职时间">
          <el-date-picker
            v-model="entrydate"
            clearable
            value-format="yyyy-MM-dd"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            size="small"
          />
        </el-form-item>

        <el-form-item>
          <el-button type="primary" icon="el-icon-search" @click="onSubmit" size="small">搜索</el-button>
          <el-button @click="clear" size="small" icon="el-icon-refresh-right">重置</el-button>
        </el-form-item>
      </el-form>
    </div>

    <!-- 内容区域 -->
    <div class="content-container">
      <div class="content-header">
        <span class="title">员工列表</span>
        <div class="action-buttons-container">
          <!-- 左侧按钮组 -->
          <div class="action-group">
            <el-button size="small" icon="el-icon-download" @click="downloadEmpTemplate" type="info">下载模板</el-button>
            <el-upload
              ref="upload"
              action="/api/file/upload/emp"
              :auto-upload="true"
              :show-file-list="false"
              :on-success="handleUploadSuccess"
              :headers="token"
              :on-error="handleUploadError"
              :before-upload="beforeUpload"
              accept=".xls,.xlsx"
              class="upload-button"
            >
              <template #trigger>
                <el-button type="success" size="small" icon="el-icon-upload2">开始导入</el-button>
              </template>
            </el-upload>
            <el-button type="warning" size="small" icon="el-icon-download" @click="exportEmpData">导出数据</el-button>
          </div>
          <!-- 右侧按钮组 -->
          <div class="action-group">
            <el-button type="primary" size="small" @click="dialogVisible = true; emp = { image: ''};" icon="el-icon-plus">新增员工</el-button>
            <el-button type="danger" size="small" @click="deleteByIds" icon="el-icon-delete">批量删除</el-button>
          </div>
        </div>
      </div>
      <!--表格-->
      <el-table :data="tableData" style="width: 100%" border @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column prop="name" label="姓名" align="center" />
        <el-table-column prop="image" label="头像" align="center">
          <template slot-scope="{ row }">
            <el-image style="width: auto; height: 40px; border: none; cursor: pointer" :src="row.image" />
          </template>
        </el-table-column>

        <el-table-column align="center" label="性别">
          <template slot-scope="scope">
            <span style="margin-right: 10px">
              {{ scope.row.gender == "1" ? "男" : "女" }}</span>
          </template>
        </el-table-column>

        <el-table-column align="center" label="职位">
          <template slot-scope="scope">
            <span v-if="scope.row.job == 1" style="margin-right: 10px">班主任</span>
            <span v-if="scope.row.job == 2" style="margin-right: 10px">讲师</span>
            <span v-if="scope.row.job == 3" style="margin-right: 10px">学工主管</span>
            <span v-if="scope.row.job == 4" style="margin-right: 10px">教研主管</span>
          </template>
        </el-table-column>

        <el-table-column align="center" label="日职日期">
          <template slot-scope="scope">
            {{ scope.row.entrydate }}
          </template>
        </el-table-column>
        <el-table-column align="center" label="最后操作时间">
          <template slot-scope="scope">
            {{ scope.row.updateTime ? scope.row.updateTime.replace('T',' '):'' }}
          </template>
        </el-table-column>

        <el-table-column align="center" label="操作">
          <template slot-scope="scope">
            <el-button type="primary" size="mini" @click="update(scope.row.id)">编辑</el-button>
            <el-button type="danger" size="mini" @click="deleteById(scope.row.id)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <!--分页工具条-->
    <div class="pagination-container">
      <el-pagination
        :background="true"
        :current-page="searchForm.page"
        :page-sizes="[5, 10, 15, 20]"
        :page-size="searchForm.pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>

    <!--添加数据对话框表单-->
    <el-dialog ref="form" title="编辑员工" :visible.sync="dialogVisible" width="30%">
      <el-form ref="form" :model="emp" label-width="80px" size="mini">
        <el-form-item label="用户名">
          <el-input v-model="emp.username" />
        </el-form-item>
        <el-form-item label="员工姓名">
          <el-input v-model="emp.name" />
        </el-form-item>

        <el-form-item label="性别">
          <el-select v-model="emp.gender" placeholder="请选择" style="width:100%">
            <el-option
              v-for="item in genderList"
              :key="item.value"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="头像">
          <el-upload
            class="avatar-uploader"
            action="/api/file"
            :headers="token"
            name="image"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload"
          >
            <img v-if="emp.image" :src="emp.image" class="avatar">
            <i v-else class="el-icon-plus avatar-uploader-icon" />
          </el-upload>
        </el-form-item>

        <el-form-item label="职位">
          <el-select v-model="emp.job" placeholder="请选择" value-key="emp.job" style="width:100%">
            <el-option
              v-for="item in jobList"
              :key="item.value"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="入职日期">
          <el-date-picker
            v-model="emp.entrydate"
            clearable
            type="date"
            placeholder="选择日期"
            size="small"
            style="width:100%"
          />
        </el-form-item>

        <el-form-item label="归属部门">
          <el-select v-model="emp.deptId" placeholder="请选择" style="width:100%">
            <el-option
              v-for="item in deptList"
              :key="item.value"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="add">提交</el-button>
          <el-button @click="dialogVisible = false">取消</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
  </div>
</template>

<script>
import { page, add, update, deleteById, selectById } from '@/api/emp.js'
import { findAll } from '@/api/dept.js'
import { getToken } from '@/utils/auth'

export default {
  data() {
    return {
      // 品牌模型数据
      searchForm: {
        name: '',
        gender: '',
        page: 1,
        pageSize: 5,
        beginTime: '',
        endTime: ''
      },
      entrydate: [], // daterange picker
      total: 0,
      dialogVisible: false,
      emp: {
        image: ''
      },
      deptList: [],
      genderList: [{ id: 1, name: '男' }, { id: 2, name: '女' }],
      jobList: [
        {
          id: 1,
          name: '班主任'
        },
        {
          id: 2,
          name: '讲师'
        },
        {
          id: 3,
          name: '学工主管'
        },
        {
          id: 4,
          name: '教研主管'
        }
      ],
      // 被选中的id数组
      selectedIds: [],
      // 复选框选中数据集合
      multipleSelection: [],
      // 表格数据
      tableData: [],
      token: { token: getToken() },
      exporting: false
    }
  },

  watch: {
    entrydate(val) {
      if (val && val.length >= 2) {
        this.searchForm.beginTime = val[0]
        this.searchForm.endTime = val[1]
      } else {
        this.searchForm.beginTime = ''
        this.searchForm.endTime = ''
      }
    }
  },

  mounted() {
    this.page() // 当页面加载完成后，发送异步请求，获取数据
    findAll().then((result) => {
      this.deptList = result.data.data
    })
  },

  methods: {
    // 查询分页数据
    page() {
      page(this.searchForm).then((res) => {
        this.total = res.data.data.total
        this.tableData = res.data.data.rows
      })
    },

    // 复选框选中后执行的方法
    handleSelectionChange(val) {
      this.multipleSelection = val
    },

    // 查询方法
    onSubmit() {
      this.searchForm.page = 1
      this.page()
    },

    clear() {
      this.searchForm = {
        name: '',
        gender: '',
        page: 1,
        pageSize: 5,
        beginTime: '',
        endTime: ''
      }
      this.entrydate = []
      this.page()
    },
    // 添加数据
    add() {
      let operator

      if (this.emp.id) {
        // 修改
        operator = update(this.emp)
      } else {
        operator = add(this.emp)
      }

      operator.then((resp) => {
        if (resp.data.code === 1) {
          this.dialogVisible = false
          this.page()
          this.$message({ message: '恭喜你，保存成功', type: 'success' })
          this.emp = { image: '' }
        } else {
          this.$message.error(resp.data.msg)
        }
      })
    },
    update(id) {
      // 1. 打开窗口
      this.dialogVisible = true
      // 2. 发送请求

      selectById(id).then((result) => {
        if (result.data.code === 1) {
          this.emp = result.data.data
        }
      })
    },

    // 分页
    handleSizeChange(val) {
      // 重新设置每页显示的条数
      this.searchForm.pageSize = val
      this.page()
    },

    handleCurrentChange(val) {
      // 重新设置当前页码
      this.searchForm.page = val
      this.page()
    },

    // 删除员工信息
    deleteById(id) {
      this.$confirm('此操作将删除该数据, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        // 2. 发送AJAX请求
        deleteById(id).then((resp) => {
          if (resp.data.code === 1) {
            // 删除成功
            this.$message.success('恭喜你，删除成功')
            this.page()
          } else {
            this.$message.error(resp.data.msg)
          }
        })
      }).catch(() => {
        // 用户点击取消按钮
        this.$message.info('已取消删除')
      })
    },

    // 批量删除员工信息
    deleteByIds() {
      // 弹出确认提示框
      this.$confirm('此操作将删除该数据, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        // 用户点击确认按钮
        // 1. 创建id数组, 从 this.multipleSelection 获取即可
        for (let i = 0; i < this.multipleSelection.length; i++) {
          this.selectedIds[i] = this.multipleSelection[i].id
        }

        // 2. 发送AJAX请求
        deleteById(this.selectedIds).then((resp) => {
          if (resp.data.code === 1) {
            // 删除成功
            this.$message.success('恭喜你，删除成功')
            this.page()
          } else {
            this.$message.error(resp.data.msg)
          }
        })
      }).catch(() => {
        // 用户点击取消按钮
        this.$message.info('已取消删除')
      })
    },

    // 文件上传相关
    handleAvatarSuccess(res, file) {
      this.emp.image = res.data
    },
    beforeAvatarUpload(file) {
      const isJPG = file.type === 'image/jpeg'
      const isLt2M = file.size / 1024 / 1024 < 2
      if (!isJPG) {
        this.$message.error('上传头像图片只能是 JPG 格式!')
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!')
      }
      return isJPG && isLt2M
    },
    downloadEmpTemplate() {
      const link = document.createElement('a')
      link.href = '/api/file/downloadEmp'
      link.setAttribute('download', '员工导入模板.xlsx')
      document.body.appendChild(link)
      link.click()
      link.remove()
    },
    beforeUpload(file) {
      const isValidType = file.type === 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' ||
        file.type === 'application/vnd.ms-excel'
      if (!isValidType) {
        this.$message.error('只能上传 Excel 文件!')
      }
      return isValidType
    },
    handleUploadSuccess(response, file) {
      if (response.code === 1) {
        this.$message.success(response.msg || '导入成功')
        this.page()
      } else {
        this.$message.error(response.msg || '导入失败')
      }
    },
    handleUploadError() {
      this.$message.error('文件上传失败，请重试。')
    },
    exportEmpData() {
      this.exporting = true
      const xhr = new XMLHttpRequest()
      xhr.open('GET', '/api/file/exportExcelEmp', true)
      xhr.responseType = 'blob'

      // 设置请求头，携带 token
      xhr.setRequestHeader('token', localStorage.getItem('token'))

      xhr.onload = () => {
        if (xhr.status === 200) {
          const url = window.URL.createObjectURL(new Blob([xhr.response]))
          const link = document.createElement('a')
          link.href = url
          link.setAttribute('download', '员工数据.xlsx')
          document.body.appendChild(link)
          link.click()
          document.body.removeChild(link)
          window.URL.revokeObjectURL(url)
        } else {
          const responseText = xhr.responseText
          try {
            const json = JSON.parse(responseText)
            this.$message.error(json.msg || '导出失败，请稍后再试')
          } catch (e) {
            this.$message.error('导出失败，请稍后再试')
          }
        }
        this.exporting = false
      }
      xhr.onerror = () => {
        this.$message.error('导出失败，请稍后再试')
        this.exporting = false
      }
      xhr.send()
    }
  }
}
</script>
<style scoped>
.app-container {
  padding: 20px;
  background-color: #f0f2f5;
}

.search-container {
  background-color: #fff;
  padding: 20px;
  border-radius: 4px;
  box-shadow: 0 1px 4px rgba(0, 21, 41, 0.08);
  margin-bottom: 20px;
}

.search-form {
  display: flex;
  flex-wrap: wrap;
  align-items: center;
}

.search-form .el-form-item {
  margin-bottom: 0;
  margin-right: 20px;
  vertical-align: middle;
}

.content-container {
  background-color: #fff;
  padding: 20px;
  border-radius: 4px;
  box-shadow: 0 1px 4px rgba(0, 21, 41, 0.08);
  margin-bottom: 20px;
  align-items: center;
}

.content-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.content-header .title {
  font-size: 16px;
  font-weight: bold;
}

.action-buttons-container {
  display: flex;
  justify-content: space-between;
  align-items: center;
  flex-grow: 1;
  margin-left: 20px;
}

.action-group {
  display: flex;
  align-items: center;
}

.action-group > * + * {
  margin-left: 10px;
}

.pagination-container {
  background-color: #fff;
  padding: 20px;
  border-radius: 4px;
  box-shadow: 0 1px 4px rgba(0, 21, 41, 0.08);
  text-align: right;
}

.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 100px;
  height: 100px;
  line-height: 100px;
  text-align: center;
}
.avatar {
  width: 100px;
  height: 100px;
  display: block;
}

@media (max-width: 1200px) {
  .content-header {
    flex-direction: column;
    align-items: flex-start;
  }
  .action-buttons-container {
    margin-left: 0;
    margin-top: 15px;
    width: 100%;
  }
}
@media (max-width: 768px) {
  .action-buttons-container, .action-group {
    flex-direction: column;
    align-items: flex-start;
    width: 100%;
  }
  .action-group > * {
    margin-bottom: 10px;
  }
  .action-group > * + * {
    margin-left: 0;
  }
}
</style>

<style>
/* 暗色主题适配：仅在 body.dark-theme 下生效 */
body.dark-theme .app-container,
body.dark-theme .search-container,
body.dark-theme .content-container,
body.dark-theme .pagination-container {
  background-color: #1f1f1f !important;
  color: #fff !important;
}
body.dark-theme .el-table,
body.dark-theme .el-table th,
body.dark-theme .el-table td {
  background-color: #232323 !important;
  color: #fff !important;
}
body.dark-theme .el-table th {
  background-color: #232323 !important;
  color: #fff !important;
  border-bottom: 1px solid #444 !important;
}
body.dark-theme .el-table td {
  border-bottom: 1px solid #444 !important;
}
body.dark-theme .el-table .el-table__row:hover {
  background-color: #2b2b2b !important;
}
body.dark-theme .el-input__inner,
body.dark-theme .el-select .el-input__inner {
  background-color: #232323 !important;
  color: #fff !important;
  border-color: #444 !important;
}
body.dark-theme .el-button--primary {
  background-color: #409eff !important;
  border-color: #409eff !important;
  color: #fff !important;
}
body.dark-theme .el-button--danger {
  background-color: #f56c6c !important;
  border-color: #f56c6c !important;
  color: #fff !important;
}
body.dark-theme .el-button--success {
  background-color: #67c23a !important;
  border-color: #67c23a !important;
  color: #fff !important;
}
body.dark-theme .el-button--info {
  background-color: #909399 !important;
  border-color: #909399 !important;
  color: #fff !important;
}
body.dark-theme .el-button--warning {
  background-color: #e6a23c !important;
  border-color: #e6a23c !important;
  color: #fff !important;
}
body.dark-theme .el-pagination,
body.dark-theme .el-pagination__total,
body.dark-theme .el-pagination__jump,
body.dark-theme .el-pagination__editor,
body.dark-theme .el-pagination__sizes,
body.dark-theme .el-pagination__sizes .el-input__inner {
  background-color: #1f1f1f !important;
  color: #fff !important;
  border-color: #444 !important;
}
body.dark-theme .el-dialog {
  background-color: #232323 !important;
  color: #fff !important;
}
body.dark-theme .el-dialog__header {
  background-color: #232323 !important;
  color: #fff !important;
  border-bottom: 1px solid #444 !important;
}
body.dark-theme .el-dialog__title {
  color: #fff !important;
}
body.dark-theme .el-dialog__body {
  background-color: #232323 !important;
  color: #fff !important;
}
body.dark-theme .el-form-item__label {
  color: #fff !important;
}
body.dark-theme .el-select-dropdown {
  background-color: #232323 !important;
  color: #fff !important;
}
body.dark-theme .el-select-dropdown__item.selected {
  background-color: #409eff !important;
  color: #fff !important;
}
body.dark-theme .el-select-dropdown__item:hover {
  background-color: #2b2b2b !important;
  color: #fff !important;
}
</style>
